﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Common;
using Controllers.Extend;
using Controllers.Filter;
using Model.Sys.Config;
using Newtonsoft.Json;
using SearchModel;
using ViewModel;

namespace Controllers.Areas.Role.Controllers
{
    public class ManagerController : UserBaseController
    {
        protected override void OnAuthorization(AuthorizationContext filterContext)
        {
            cookieName = CookieConfig.UserInfoLoginCookieName;
            base.OnAuthorization(filterContext);

            if (loginUser == null)
            {
                if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
                {
                    filterContext.Result = new JsonResult()
                    {
                        ContentEncoding = Encoding.UTF8,
                        Data = new ResultModel
                        {
                            Pass = false,
                            Msg = "对不起，您的身份验证过时，请重新登录。"
                        },
                        JsonRequestBehavior = JsonRequestBehavior.AllowGet
                    };
                }
                else
                {
                    filterContext.Result = new ContentResult() { Content = "<script>alert('对不起，您的身份验证过时，请重新登录。');top.location='/Login/Index';</script>" };
                }
            }
        }
        
        /// <summary>
        /// 角色管理的列表页面
        /// </summary>
        /// <param name="powerId"></param>
        /// <returns></returns>
        [Power(PowerId = "01000200")]
        public ActionResult Index(string powerId)
        {
            ViewData["powerId"] = powerId;
            return View();
        }

        /// <summary>
        /// 角色管理的列表页面的列表查询
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public ActionResult Search(DataTable dt)
        {
            int total;
            int pageSize = dt.length;
            int pageIndex = dt.pageIndex;
            SMRole smRole = JsonConvert.DeserializeObject<SMRole>(dt.searchStr);

            List<Model.Database.Role> roleList = CurrentBllSession.RoleBll.GetListBySearchPage(pageIndex, pageSize, out total, smRole);
            dt.recordsTotal = total;
            dt.recordsFiltered = total;
            dt.data = roleList;

            return Json(dt);
        }

        /// <summary>
        /// 增加角色页面
        /// </summary>
        /// <returns></returns>
        [Power(PowerId = "01000201")]
        public ActionResult Add()
        {
            return View();
        }

        /// <summary>
        /// 增加角色页面的提交
        /// </summary>
        /// <param name="pmRole"></param>
        /// <returns></returns>
        public ActionResult AddSubmit(Model.Database.Role pmRole)
        {
            ResultModel rm = new ResultModel();
            string powerIdStr=Request["PowerIdStr"];

            if (!string.IsNullOrEmpty(pmRole.RoleName))
            {
                Model.Database.Role role = pmRole;
                role.RoleId = StringHelper.GetGuidString();
                role.Powers = MakePowerList(powerIdStr);
                role.AddTime = DateTime.Now;
                CurrentBllSession.RoleBll.AddRoleAndRole_Power(role);
                rm.Pass = true;
                rm.Msg = "添加成功";
            }
            else
            {
                rm.Pass = false;
                rm.Msg = "请填写完整信息";
            }

            return Json(rm);
        }

        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="idArrStr"></param>
        /// <returns></returns>
        [Power(PowerId = "01000202")]
        public ActionResult Delete(string idArrStr)
        {
            ResultModel rm = new ResultModel();

            string[] idArr = idArrStr.Split(',');
            CurrentBllSession.RoleBll.ListDelete(idArr);
            rm.Pass = true;
            rm.Msg = "删除成功";

            return Json(rm);
        }

        /// <summary>
        /// 修改角色页面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Power(PowerId = "01000203")]
        public ActionResult Edit(string id)
        {
            if (!string.IsNullOrEmpty(id))
            {
                Model.Database.Role role = CurrentBllSession.RoleBll.GetEntity(id);
                return View(role);
            }
            else
            {
                return Content("id参数无效");
            }
        }

        /// <summary>
        /// 修改角色页面的树状权限（标记已选权限）
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult MenuBtnCheckedList(string id)
        {
            IQueryable<Model.Database.Power> powerIq = CurrentBllSession.PowerBll.GetIQueryable();
            List<Model.Database.Power> powerList = powerIq.ToList();
            List<ZTreeModel> menuBtnList = MakeMenuBtnList(powerList);
            List<Model.Database.Power> powerCheckedList= CurrentBllSession.RoleBll.GetPower(id);
            foreach (var powerChecked in powerCheckedList)
            {
                menuBtnList.FirstOrDefault(a => a.id == powerChecked.PowerId).@checked = true;
            }

            return Json(menuBtnList);
        }

        /// <summary>
        /// 修改角色页面的提交
        /// </summary>
        /// <param name="pmRole"></param>
        /// <returns></returns>
        public ActionResult EditSubmit(Model.Database.Role pmRole)
        {
            ResultModel rm = new ResultModel();
            string id = Request["id"];
            string powerIdStr = Request["powerIdStr"];

            if ((!string.IsNullOrEmpty(pmRole.RoleName)))
            {
                Model.Database.Role roleOld = CurrentBllSession.RoleBll.GetEntity(id);
                roleOld.Powers=CurrentBllSession.RoleBll.GetPower(id);
                roleOld.RoleName = pmRole.RoleName;
                roleOld.Description = pmRole.Description;
                roleOld.Powers = MakePowerList(powerIdStr);
                roleOld.ModifyTime = DateTime.Now;
                CurrentBllSession.RoleBll.UpdateRoleAndRole_Power(roleOld);
                rm.Pass = true;
                rm.Msg = "保存成功";
            }
            else
            {
                rm.Pass = false;
                rm.Msg = "请填写必要信息";
            }

            return Json(rm);
        }

        /// <summary>
        /// 查看角色页面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Power(PowerId = "01000204")]
        public ActionResult View(string id)
        {
            if (!string.IsNullOrEmpty(id))
            {
                Model.Database.Role role = CurrentBllSession.RoleBll.GetEntity(id);
                return View(role);
            }
            else
            {
                return Content("id参数无效");
            }
        }


        #region 私有方法
        /// <summary>
        /// 制作权限集合
        /// </summary>
        private ICollection<Model.Database.Power> MakePowerList(string powerIdStr)
        {
            List<Model.Database.Power> powerList = new List<Model.Database.Power>();
            if (!string.IsNullOrEmpty(powerIdStr))
            {
                string[] powerIdArr = StringHelper.DelLastChar(powerIdStr, ",").Split(',');

                powerList = CurrentBllSession.PowerBll.GetPowerListByIdArr(powerIdArr);
            }

            return powerList;
        }

        /// <summary>
        /// 制作菜单按钮集合
        /// </summary>
        private List<ZTreeModel> MakeMenuBtnList(List<Model.Database.Power> powerList)
        {
            List<Model.Database.Power> treeSortList = new List<Model.Database.Power>();
            List<ZTreeModel> menuBtnList = new List<ZTreeModel>();

            TreeSortList(powerList, treeSortList,"0");
            foreach (var power in treeSortList)
            {
                ZTreeModel menu = new ZTreeModel() { id = power.PowerId, pId = power.ParentId, name = power.PowerName };
                menuBtnList.Add(menu);
            }

            return menuBtnList;
        }

        /// <summary>
        /// 树状排序集合（递归）
        /// </summary>
        private void TreeSortList(List<Model.Database.Power> powerList, List<Model.Database.Power> treeSortPowerList, string parentId)
        {
            foreach (var power in powerList.Where(a => a.ParentId == parentId).OrderBy(a => a.Sort))//菜单
            {
                treeSortPowerList.Add(power);
               
                TreeSortList(powerList, treeSortPowerList, power.PowerId);

            }
        }
        #endregion

    }
}
